package com.yunbiao.ybbusstopplate.utils.net;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;


import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.example.library_hy_advert.system.Path;
import com.yunbiao.ybbusstopplate.R;
import com.yunbiao.ybbusstopplate.base.APP;
import com.yunbiao.ybbusstopplate.base.BaseActivity;
import com.yunbiao.ybbusstopplate.base.Constants;
import com.yunbiao.ybbusstopplate.base.HeartBeatClient;
import com.yunbiao.ybbusstopplate.base.LayoutResEntity;
import com.yunbiao.ybbusstopplate.message.DownCompleteEvent;
import com.yunbiao.ybbusstopplate.ui.dialog.LoadingDialog;
import com.yunbiao.ybbusstopplate.utils.CommonUtils;
import com.yunbiao.ybbusstopplate.utils.SpTool;
import com.yunbiao.ybbusstopplate.utils.cache.ACache;
import com.yunbiao.ybbusstopplate.utils.cache.LayoutCache;
import com.yunbiao.ybbusstopplate.utils.core.DownListener;
import com.yunbiao.ybbusstopplate.utils.core.DownloadCounter;
import com.yunbiao.ybbusstopplate.utils.core.DownloadSpeed;
import com.yunbiao.ybbusstopplate.utils.core.NetSpeed;
import com.yunbiao.ybbusstopplate.utils.core.SSTool;
import com.yunbiao.ybbusstopplate.utils.core.TYTool;
import com.yunbiao.ybbusstopplate.utils.core.VersionUpdateConstants;
import com.yunbiao.ybbusstopplate.utils.core.play.ImageDetail;
import com.yunbiao.ybbusstopplate.utils.core.play.LayoutInfo;
import com.yunbiao.ybbusstopplate.utils.xutil.MyXutils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;


import java.io.File;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ResourceUpdate {

    private static final String TAG = "ResourceUpdate";

    private static String WEB_BASE_URL = Constants.RESOURCE_URL;

    private LayoutInfo layoutInfo;

    /**
     * 资源获取
     **/
    private static String RESOURCE_URL = WEB_BASE_URL + "device/service/getresource.html";

    /**
     * 广告资源获取
     **/
    private static String ADS_RESOURCE_URL = WEB_BASE_URL + "api/share/getDeviceAdvert.html";

    /**
     * 判断服务器和本地布局是否匹配
     **/
    public static String LAYOUT_CHANGE_STATUS = WEB_BASE_URL + "device/service/layoutchangestatus.html";

    /**
     * 判断服务器中的设备是否在线
     **/
    public static String DEVICE_ONLINE_STATUS = WEB_BASE_URL + "device/status/getrunstatus.html";

    /**
     * 前端布局
     */
    private static String LAYOUT_MENU_URL = WEB_BASE_URL + "device/service/getLayoutMenu.html";

    /**
     * 天气获取
     **/
//    public static String WEATHER_URL = WEB_BASE_URL + "weather/city.html";
    public static String WEATHER_URL = WEB_BASE_URL + "weather/getCityWeather.html";

    /**
     * 限号获取
     **/
    public static String CARRUN_URL = WEB_BASE_URL + "weather/carrun.html";

    /**
     * 外币汇率获取
     **/
    public static String RMBRATE_URL = WEB_BASE_URL + "weather/exrate.html";

    /**
     * 版本检测
     **/
//    public static String VERSION_URL = WEB_BASE_URL + "device/service/getversion.html";
    public static String VERSION_URL = Constants.VERSION_BASE_URL + "device/service/getversion.html";
    /**
     * 开关机时间获取
     **/
    public static String POWER_OFF_URL = WEB_BASE_URL + "device/service/poweroff.html";
    /**
     * 多时段开关机获取
     */
    public static String MULTI_POWER_OFF_URL = WEB_BASE_URL + "api/deviceTiming/timing.html";

    /**
     * 截图上传
     **/
    public static String SCREEN_UPLOAD_URL = WEB_BASE_URL + "device/service/uploadScreenImg.html";

    /**
     * 上传进度
     **/
    public static String RES_UPLOAD_URL = WEB_BASE_URL + "device/service/rsupdate.html";

    /**
     * SER_NUMBER
     **/
    public static String SER_NUMBER = WEB_BASE_URL + "device/status/getHasNumber.html";

    public static String SCAN_TO_CALL = WEB_BASE_URL + "/mobilebusself/mobilebusselfpost/selectbyordersernum.html";

    public static String SETTIME = WEB_BASE_URL + "common/service/getSystemTime.html";

    /**
     * 绑定设备
     */
    public static String DEC_NUM = WEB_BASE_URL + "device/status/binduser.html";

    /**
     * 获取续费二维码
     */
    public static String QRCODE = WEB_BASE_URL + "device/renewal/getopenrenewalqrcode.html";

    /**
     * 上传人脸识别
     */
    public static String UPLOADFACE = WEB_BASE_URL + "visitors/saveVisitors.html";

    /**
     * 上传下载进度
     */
    public static String NETSPEEFURL = WEB_BASE_URL + "device/status/uploadnetspeed.html";

    /**
     * 广告播放日志上传
     */
    public static String RECEIVELOGFILE_URL = WEB_BASE_URL + "api/loginterface/insertLogFace.html";

    public static String UPLOADTEMP_URL = WEB_BASE_URL + "api/devicetemp/uploadtemp.html";//户外广告机实时温度上传

    public static String OUTDOORCONFIG_URL = WEB_BASE_URL + "/api/devicetemp/gettemp.html";//户外广告机配置
    public static String UPDATEDEVICETYPE_URL = WEB_BASE_URL + "/device/status/updateDeviceType.html";//广告机类型更新

    public static String SYNCTEMP_URL = WEB_BASE_URL + "/api/devicetemp/syncTemp.html";//户外广告机本地配置同步

    /**
     * 音量调节值获取
     * http://tyiyun.com/device/service/getVolume.html?deviceId=ffffffff-
     * be09-eca9-756a-0d8000000000
     */
    private static String VOLUME_URL = WEB_BASE_URL + "device/service/getVolume.html";
    private static String UPLOAD_APP_VERSION_URL = WEB_BASE_URL + "device/service/uploadAppVersionNew.html";

    private static String UPLOAD_DISK_URL = WEB_BASE_URL + "device/service/uploadDisk.html";

//    private static String CACHE_BASE_PATH = "/mnt/sdcard/hsd/";
//    public static String IMAGE_CACHE_PATH = CACHE_BASE_PATH + "resource/";// 资源存储目录

//    public static String WEI_CACHE_PATH = CACHE_BASE_PATH + "wei/";// 资源存储目录
//    public static String PROPERTY_CACHE_PATH = CACHE_BASE_PATH + "property/";// 参数缓存存储目录

//    public static String PROPERTY_CACHE_PATH_BOTTOM = CACHE_BASE_PATH + "propertyBottom/";// 参数缓存bottom存储目录
//    public static String SCREEN_CACHE_PATH = CACHE_BASE_PATH + "screen/";//参数缓存存储目录
//    public static String PUSH_CACHE_PATH = CACHE_BASE_PATH + "push/";// 资源存储目录

//    public static String PLAYLOG_PATH = CACHE_BASE_PATH + "playLog/";//广告播放日志存储目录

//    public static String RESOURSE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();

//    public static void setNewResourcePath(boolean innerSd) {
//        if (innerSd) {
//            RESOURSE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
//        } else {
//            String path = TYTool.getSdcardPath();
//            if (!TextUtils.isEmpty(path)) {
//                RESOURSE_PATH = path;
//            }
//        }
//    }

    public static void initWebConnect() {
        WEB_BASE_URL = Constants.RESOURCE_URL;
        Log.e(TAG, "initWebConnect: ------WEB_BASE_URL--------------》" + WEB_BASE_URL);
        RESOURCE_URL = WEB_BASE_URL + "device/service/getresource.html";
        LAYOUT_MENU_URL = WEB_BASE_URL + "device/service/getLayoutMenu.html";
//        WEATHER_URL = WEB_BASE_URL + "weather/city.html";
        WEATHER_URL = WEB_BASE_URL + "weather/getCityWeather.html";
        VERSION_URL = WEB_BASE_URL + "device/service/getversion.html";
        POWER_OFF_URL = WEB_BASE_URL + "device/service/poweroff.html";
        SCREEN_UPLOAD_URL = WEB_BASE_URL + "device/service/uploadScreenImg.html";
        RES_UPLOAD_URL = WEB_BASE_URL + "device/service/rsupdate.html";
        SER_NUMBER = WEB_BASE_URL + "device/status/getHasNumber.html";
        VOLUME_URL = WEB_BASE_URL + "device/service/getVolume.html";
        UPLOAD_APP_VERSION_URL = WEB_BASE_URL + "device/service/uploadAppVersionNew.html";
        UPLOAD_DISK_URL = WEB_BASE_URL + "device/service/uploadDisk.html";
        SETTIME = WEB_BASE_URL + "common/service/getSystemTime.html";
        DEC_NUM = WEB_BASE_URL + "device/status/binduser.html";
        RMBRATE_URL = WEB_BASE_URL + "weather/exrate.html";
        QRCODE = WEB_BASE_URL + "device/renewal/getopenrenewalqrcode.html";
        CARRUN_URL = WEB_BASE_URL + "weather/carrun.html";
        ADS_RESOURCE_URL = WEB_BASE_URL + "api/share/getDeviceAdvert.html";
        //4.4.4 后加入**********************************
        LAYOUT_CHANGE_STATUS = WEB_BASE_URL + "device/service/layoutchangestatus.html";
        DEVICE_ONLINE_STATUS = WEB_BASE_URL + "device/status/getrunstatus.html";
        SCAN_TO_CALL = WEB_BASE_URL + "/mobilebusself/mobilebusselfpost/selectbyordersernum.html";
        UPLOADFACE = WEB_BASE_URL + "visitors/saveVisitors.html";
        NETSPEEFURL = WEB_BASE_URL + "device/status/uploadnetspeed.html";
        RECEIVELOGFILE_URL = WEB_BASE_URL + "api/loginterface/insertLogFace.html";
        MULTI_POWER_OFF_URL = WEB_BASE_URL + "api/deviceTiming/timing.html";
    }

    /**
     * 下载进度完成
     */
    public static void finishUpLoad() {
        Map<String, String> netSpeed = new HashMap<String, String>();
        netSpeed.put("deviceNo", HeartBeatClient.getDeviceNo());
        netSpeed.put("speed", "-1");
        MyXutils.getInstance().post(NETSPEEFURL, netSpeed, new MyXutils.XCallBack() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onError(Throwable ex) {

            }

            @Override
            public void onFinish() {

            }
        });
    }

    /**
     * 实时下载进度
     * 上传到服务器
     */

    static void upToServer(String speedStr) {
        Map<String, String> netSpeed = new HashMap<String, String>();
        netSpeed.put("deviceNo", HeartBeatClient.getDeviceNo());
        netSpeed.put("speed", speedStr);
        MyXutils.getInstance().post(NETSPEEFURL, netSpeed, new MyXutils.XCallBack() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onError(Throwable ex) {

            }

            @Override
            public void onFinish() {

            }
        });
    }

//    /**
//     * 音量调节
//     * <p/>
//     * param uid
//     */
//    public static void setVolume(String uid) {
//        HashMap<String, String> paramMap = new HashMap<String, String>();
//        paramMap.put("deviceId", uid);
//        String volume = NetTool.sendPost(VOLUME_URL, paramMap);
//        Double volumeD = Double.parseDouble(volume);
//        SoundControl.setMusicSound(volumeD);
//    }

    public static void uploadAppVersion() {
//        String versionName = CommonUtils.getAppVersion(BaseActivity.getActivity());
        String versionName = CommonUtils.getAppVersion(APP.Companion.getAppContext());
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TYTool.showTitleTip("版本:" + versionName);
            }
        });

        HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("deviceNo", HeartBeatClient.getDeviceNo());
        paramMap.put("version", versionName);
        paramMap.put("type", VersionUpdateConstants.CURRENT_VERSION + "");
        MyXutils.getInstance().post(UPLOAD_APP_VERSION_URL, paramMap, new MyXutils.XCallBack() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onError(Throwable ex) {

            }

            @Override
            public void onFinish() {

            }
        });
    }

    /**
     * 上传磁盘数据
     */
    public static void uploadDiskInfo() {
        String diskInfo = TYTool.getSDDiskCon();
        String ss = "磁盘:" + diskInfo;
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TYTool.showTitleTip(ss);
            }
        });

        HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("deviceNo", HeartBeatClient.getDeviceNo());
        paramMap.put("diskInfo", diskInfo);
        LogUtils.d(TAG, "-------------------磁盘空间------------------------");
        LogUtils.d(TAG, "访问：url:" + UPLOAD_DISK_URL + ",deviceNo:" + paramMap.get("deviceNo"));
        MyXutils.getInstance().post(UPLOAD_DISK_URL, paramMap, new MyXutils.XCallBack() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(TAG, "成功：" + result);
            }

            @Override
            public void onError(Throwable ex) {
                LogUtils.d(TAG, "失败：" + ex.getMessage());
            }

            @Override
            public void onFinish() {

            }
        });
    }

    public static String getSDDiskCon() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            File sdcardDir = Environment.getExternalStorageDirectory();
            StatFs sf = new StatFs(sdcardDir.getPath());
            double blockSize = sf.getBlockSize();
            double blockCount = sf.getBlockCount();
            double availCount = sf.getAvailableBlocks();

            Double level = (availCount * blockSize / 1024);
            Double all = (blockSize * blockCount / 1024);

            Double use = all - level;

            Double useDou = use / 1024 / 1024;
//            Double levelDou = level / 1024 / 1024;
            Double allDou = all / 1024 / 1024;

            BigDecimal useB = new BigDecimal(useDou);
            double useF = useB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

//            BigDecimal levelB = new BigDecimal(levelDou);
//            double levelF = levelB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            BigDecimal allB = new BigDecimal(allDou);
            double allF = allB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            String useStr = useF + "G";
            if (useF < 1) {
                useF = useF * 1024;
                useStr = useF + "M";
            }
//            String levelStr = levelF + "G";
//            if (levelF < 1) {
//                levelF = levelF * 1024;
//                levelStr = levelF + "M";
//            }
            String allStr = allF + "G";
            if (allF < 1) {
                allF = allF * 1024;
                allStr = allF + "M";
            }
            return "已用:" + (useStr) + "/可用:" + allStr;
        } else {
            return "";
        }
    }

    public static String getEnSDDiskCon(Context context) {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            File sdcardDir = Environment.getExternalStorageDirectory();
            StatFs sf = new StatFs(sdcardDir.getPath());
            double blockSize = sf.getBlockSize();
            double blockCount = sf.getBlockCount();
            double availCount = sf.getAvailableBlocks();

            Double level = (availCount * blockSize / 1024);
            Double all = (blockSize * blockCount / 1024);

            Double use = all - level;

            Double useDou = use / 1024 / 1024;
//            Double levelDou = level / 1024 / 1024;
            Double allDou = all / 1024 / 1024;

            BigDecimal useB = new BigDecimal(useDou);
            double useF = useB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

//            BigDecimal levelB = new BigDecimal(levelDou);
//            double levelF = levelB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            BigDecimal allB = new BigDecimal(allDou);
            double allF = allB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            String useStr = useF + "G";
            if (useF < 1) {
                useF = useF * 1024;
                useStr = useF + "M";
            }
//            String levelStr = levelF + "G";
//            if (levelF < 1) {
//                levelF = levelF * 1024;
//                levelStr = levelF + "M";
//            }
            String allStr = allF + "G";
            if (allF < 1) {
                allF = allF * 1024;
                allStr = allF + "M";
            }
            return "已用:" + (useStr) + "/可用:" + allStr;
        } else {
            return "";
        }
    }

    public static void deleteOtherFile() {
//        String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
//        String savePath = sdPath + PROPERTY_CACHE_PATH;
        String layoutJson = ACache.get(new File(Path.getOnlinePropertyCache())).getAsString("layoutJson");
        //获取布局中的文件
        List allResources = getResouceList(layoutJson);

        // 获取本地磁盘已经存在的资源
        String imagePath = Path.getOnlineAdvertPath();
        File resource = new File(imagePath);
        Map<String, File> fileMap = new HashMap<String, File>();
        if (resource.exists()) {
            File[] files = resource.listFiles();
            for (File hasFile : files) {
                fileMap.put(hasFile.getName(), hasFile);
            }
        } else {
            resource.mkdirs();
        }


        //移除已经有的文件
        for (int i = 0; i < allResources.size(); i++) {
            String names = (String) allResources.get(i);
            names = names.substring(names.lastIndexOf("/") + 1, names.length());
            if (fileMap.get(names) != null) {
                fileMap.remove(names);
            }
            if (fileMap.get(names + "_ok") != null) {
                fileMap.remove(names + "_ok");
            }
        }
        //删除剩下的数据
        Set<String> keySet = fileMap.keySet();
        for (String fileTemp : keySet) {
            File hasFile = (File) fileMap.get(fileTemp);
            hasFile.delete();
        }
    }

    //网速
    private DownloadSpeed netHandler = new DownloadSpeed();


    /**
     * 获取资源
     *
     * @param deviceId
     * @return String savePath = sdPath + PROPERTY_CACHE_PATH;
     * ACache acache = ACache.get(new File(savePath));
     * acache.put("layoutJson", deviceJson);
     */
    public void getDeviceResource(String deviceId) {
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("deviceId", deviceId);
        Log.e(TAG, "getDeviceResource: ------------url------------->" + ResourceUpdate.RESOURCE_URL);
        Log.e(TAG, "getDeviceResource: ------------deviceId------------->" + deviceId);

        Log.d("net", "getDeviceResource 提交了：" + paramMap);

        MyXutils.getInstance().post(ResourceUpdate.RESOURCE_URL, paramMap, new MyXutils.XCallBack() {
            @Override
            public void onSuccess(String result) {

                Log.e(TAG, "onSuccess: --------------getDeviceResource----------》" + result);
                // 没有返回，或者请求错误
                if (result.startsWith("\"")) {
                    result = result.substring(1, result.length() - 1);
                }


                if (!result.equals("null") && !result.equals("faile") && !result.equals("[]")) {

                    boolean isCenterAdvert = false;
                    boolean isBottomAdvert = false;


                    int advertType = Integer.valueOf(SSTool.getAdvertType(result));

                    Log.d("net", "isCenterAdvertType advertType : " + Constants.IS_CENTER_ADVERT);
                    Log.d("net", "isBottomAdvertType advertType : " + Constants.IS_BOTTOM_ADVERT);

                    Log.d("net", "provide advertType : " + advertType);

                    Log.e(TAG, "onSuccess: result==" + result);

                    // 中部 save cache
                    if (advertType == Constants.IS_CENTER_ADVERT){
                        LayoutCache.putLayoutCache(result);
                    }


                    // 底部 save cache
                    if (advertType == Constants.IS_BOTTOM_ADVERT){
                        LayoutCache.putLayoutCacheBottom(result);
                    }

                }
            }

            @Override
            public void onError(Throwable ex) {
                Log.e(TAG, "onError: --------------getDeviceResource----------》" + ex.getMessage());
                ex.printStackTrace();
            }

            @Override
            public void onFinish() {
                // 中部
                String result = LayoutCache.getLayoutCacheAsString();
                downloadLocalLayoutResource(result);

                // 底部
                String resultBottom = LayoutCache.getLayoutCacheAsStringBottom();
                downloadLocalLayoutResourceBottom(resultBottom);
            }
        });
    }


    /**
     * 获取资源
     *
     * @param
     * @return String savePath = sdPath + PROPERTY_CACHE_PATH;
     * ACache acache = ACache.get(new File(savePath));
     * acache.put("layoutJson", deviceJson);
     */
//    public void getDeviceResource(String deviceId) {
//        HashMap<String, String> paramMap = new HashMap<>();
//        paramMap.put("deviceId", deviceId);
//        MyXutils.getInstance().post(ResourceUpdate.RESOURCE_URL, paramMap, new MyXutils.XCallBack() {
//            @Override
//            public void onSuccess(String result) {
//                // 没有返回，或者请求错误
//                if (result.startsWith("\"")) {
//                    result = result.substring(1, result.length() - 1);
//                }
//                if (!result.equals("null") && !result.equals("faile") && !result.equals("[]")) {
//                    Log.e(TAG, "onSuccess: result==" + result);
//                    putLayoutCache(result);
//                    downloadLocalLayoutResource(result);
//                }
//            }
//
//            @Override
//            public void onError(Throwable ex) {
//                ex.printStackTrace();
//            }
//
//            @Override
//            public void onFinish() {
//
//            }
//        });
//    }
    public void setAPPImageResource(String imageJson) {
        if (!imageJson.equals("null") && !imageJson.equals("faile") && !imageJson.equals("[]")) {
            LayoutCache.putLayoutCache(imageJson);
        }
        downloadLocalLayoutResource(imageJson);
    }

    public void downloadLocalLayoutResource(final String deviceJson) {
        try {

            Log.e(TAG, "111 downloadLocalLayoutResource------------------------- " + deviceJson);
            // 没有返回，或者请求错误
            if (!deviceJson.equals("null") && !deviceJson.equals("faile")) {
                Log.d(TAG, "downloadLocalLayoutResource: 11111111111111");
                //所有资源文件保存路径
                final String imagePath = Path.getOnlineAdvertPath();

                DownloadCounter counter = new DownloadCounter();
                counter.setAllCount(getUrlCount(deviceJson));
                //更新网速速度的显示
                NetSpeed netSpeed = new NetSpeed(ActivityUtils.getTopActivity(), netHandler, counter);
                //启动下载计数线程
                netSpeed.startCalculateNetSpeed();

                //如果有需要下载的文件
                if (counter.isEquals()) {
                    JSONArray screenArray = LayoutCache.getLayoutCacheAsArray();
                    if (screenArray != null && screenArray.length() > 0) {

                        if (SpTool.Companion.getConfigShowAdvert() && SpTool.Companion.getConfigAdvertServerType()) {
                            EventBus.getDefault().post(new DownCompleteEvent());
                        }


                    }
                } else {
                    //初始化下载完成监听
                    if (downListener == null) {
                        setDownListener(new DownListener() {
                            @Override
                            public void onComPlete() {
                                if (!TextUtils.isEmpty(deviceJson)) {
                                    Log.d("布局信息3", "222 downloadLocalLayoutResource:下载完成监听-------");
                                    JSONArray screenArray = LayoutCache.getLayoutCacheAsArray();
                                    if (screenArray != null && screenArray.length() > 0) {
//                                        EventBus.getDefault().post(new DownCompleteEvent());
                                        if (SpTool.Companion.getConfigShowAdvert() && SpTool.Companion.getConfigAdvertServerType()) {
                                            EventBus.getDefault().post(new DownCompleteEvent());
                                        }
                                    }
                                }
                            }
                        });
                    }


                    // 识别 广告位置
                    String advertCenterPath = "";
                    String advertBottomPath = "";
                    String finalPath = imagePath; // 默认下载位置
                    String result = LayoutCache.getLayoutCacheAsString();
                    int advertType = Integer.valueOf(SSTool.getAdvertType(result));

                    // 中部广告 目录
                    if (advertType == Constants.IS_CENTER_ADVERT){
                       advertCenterPath = Path.getAdvertCenterPath();
                       finalPath = advertCenterPath;
                    }else {
                        advertCenterPath = "";
                    }

                    // 底部广告 目录
                    if (advertType == Constants.IS_BOTTOM_ADVERT){
                        advertBottomPath = Path.getAdvertBottomPath();
                        finalPath = advertBottomPath;
                    }else {
                        advertBottomPath = "";
                    }


                    Log.d("net"," 触发下载 中部广告位置：" + advertCenterPath);
                    Log.d("net"," 触发下载 底部广告位置：" + advertBottomPath);

                    //当前无布局现实的时候屏幕会卡在这里
                    Log.d("net","当前下载保存路径：" + finalPath);
                    //文件下载
                    getResource(deviceJson, finalPath, counter);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void downloadLocalLayoutResourceBottom(final String deviceJson) {
        try {

            Log.e(TAG, "333 downloadLocalLayoutResource------------------------- " + deviceJson);
            // 没有返回，或者请求错误
            if (!deviceJson.equals("null") && !deviceJson.equals("faile")) {
                Log.d(TAG, "downloadLocalLayoutResourceBottom: 33333333333");
                //所有资源文件保存路径
                final String imagePath = Path.getOnlineAdvertPath();

                DownloadCounter counter = new DownloadCounter();
                counter.setAllCount(getUrlCount(deviceJson));
                //更新网速速度的显示
                NetSpeed netSpeed = new NetSpeed(ActivityUtils.getTopActivity(), netHandler, counter);
                //启动下载计数线程
                netSpeed.startCalculateNetSpeed();

                //如果有需要下载的文件
                if (counter.isEquals()) {
                    JSONArray screenArray = LayoutCache.getLayoutCacheAsArrayBottom();
                    if (screenArray != null && screenArray.length() > 0) {

                        if (SpTool.Companion.getConfigShowAdvert() && SpTool.Companion.getConfigAdvertServerType()) {
                            EventBus.getDefault().post(new DownCompleteEvent());
                        }


                    }
                } else {
                    //初始化下载完成监听
                    if (downListener == null) {
                        setDownListener(new DownListener() {
                            @Override
                            public void onComPlete() {
                                if (!TextUtils.isEmpty(deviceJson)) {
                                    Log.d("布局信息3", "444 downloadLocalLayoutResource:下载完成监听-------");
                                    JSONArray screenArray = LayoutCache.getLayoutCacheAsArrayBottom();
                                    if (screenArray != null && screenArray.length() > 0) {
//                                        EventBus.getDefault().post(new DownCompleteEvent());
                                        if (SpTool.Companion.getConfigShowAdvert() && SpTool.Companion.getConfigAdvertServerType()) {
                                            EventBus.getDefault().post(new DownCompleteEvent());
                                        }
                                    }
                                }
                            }
                        });
                    }


                    // 识别 广告位置
                    String advertCenterPath = "";
                    String advertBottomPath = "";
                    String finalPath = imagePath; // 默认下载位置
                    String result = LayoutCache.getLayoutCacheAsStringBottom();
                    int advertType = Integer.valueOf(SSTool.getAdvertType(result));

                    // 中部广告 目录
                    if (advertType == Constants.IS_CENTER_ADVERT){
                        advertCenterPath = Path.getAdvertCenterPath();
                        finalPath = advertCenterPath;
                    }else {
                        advertCenterPath = "";
                    }

                    // 底部广告 目录
                    if (advertType == Constants.IS_BOTTOM_ADVERT){
                        advertBottomPath = Path.getAdvertBottomPath();
                        finalPath = advertBottomPath;
                    }else {
                        advertBottomPath = "";
                    }


                    Log.d("net"," 触发下载 中部广告位置：" + advertCenterPath);
                    Log.d("net"," 触发下载 底部广告位置：" + advertBottomPath);

                    //当前无布局现实的时候屏幕会卡在这里
                    Log.d("net","当前下载保存路径：" + finalPath);
                    //文件下载
                    getResource(deviceJson, finalPath, counter);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DownListener downListener;

    public static void setDownListener(DownListener downListener) {
        ResourceUpdate.downListener = downListener;
    }


    public void uploadFinishDown(String contentJson, String sdPath) {
        List<String> resouceList = getResouceList(contentJson);
        if (resouceList == null || resouceList.size() <= 0) {
            //无需下载资源
            return;
        }
        if (!new File(sdPath).exists()) {
            //储存文件不存在
            return;
        }

        List<String> downList = new ArrayList<>();
        for (int i = 0; i < resouceList.size(); i++) {
            String url = resouceList.get(i);
            String fileName = url.substring(url.lastIndexOf("/") + 1, url.length());

            File downFile = new File(sdPath + fileName + "_ok");
            if (downFile.exists()) {
                downList.add(sdPath + fileName);
            }
        }
        if (resouceList.size() != downList.size()) {
            //没有全部下载
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("rsUpdate", downList.size() + "/" + resouceList.size());
        map.put("sid", HeartBeatClient.getDeviceNo());
        map.put("userFile", resouceList.get(resouceList.size() - 1).replaceAll("\\\\", "/"));
        map.put("status", "1");

        MyXutils.getInstance().post(ResourceUpdate.RES_UPLOAD_URL, map, new MyXutils.XCallBack() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onError(Throwable ex) {

            }

            @Override
            public void onFinish() {

            }
        });
    }

    /**
     * 下载资源
     *
     * @param contentJson
     * @param sdPath
     */
    public void getResource(String contentJson, String sdPath, DownloadCounter counter) {
        Log.d("net", " 检查下载路径：" + sdPath);
        sdPath = sdPath + "/";
        Log.e(TAG, "getResource---------contentJson--------->" + contentJson);
        try {
            // 获取本地磁盘已经存在的资源
            File resource = new File(sdPath);
            Map<String, File> fileMap = new HashMap<>();

            if (resource.exists()) {
                Log.d("net", "资源路径已存在");
                File[] files = resource.listFiles();
                for (File hasFile : files) {
                    if (!hasFile.getName().contains("_ok")) {
                        fileMap.put(hasFile.getName(), hasFile);
                    }
                }
            } else {
                resource.mkdirs();
            }

            //下载所有的文件
            List<String> allDownloadList = getResouceList(contentJson);
            for (int i = 0; i < allDownloadList.size(); i++) {
                String url = allDownloadList.get(i);
                String fileName = url.substring(url.lastIndexOf("/") + 1, url.length());
                if (fileMap.get(fileName) != null) {
                    fileMap.remove(fileName);
                }
                FileCacheTool.downWebCacheFile(url, sdPath + fileName, counter);
            }
            JSONArray layoutArray = new JSONArray(contentJson);
            JSONTokener jsonParser = new JSONTokener(layoutArray.getJSONObject(0).toString());
            JSONObject urlJsonObj = (JSONObject) jsonParser.nextValue();
            Integer resClearModel = urlJsonObj.getInt("resClearModel");
            if (resClearModel == 1) {// 如果开启的是删除模式就进行删除不在当前布局里的文件资源
                // 删除不在当前资源的文件
                Set<String> keySet = fileMap.keySet();
                for (String fileTemp : keySet) {
                    File hasFile = (File) fileMap.get(fileTemp);
                    // TODO: 2/8/2024 为啥要删除？ 部署时删除以下注释？
                    //hasFile.delete();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static List getAllLayoutFiles(String content, String rules) {
        List<String> allResourList = new ArrayList<String>();
        if (TextUtils.isEmpty(content)) {
            return allResourList;
        }
        Pattern pattern = Pattern.compile(rules);
        Matcher matcher = pattern.matcher(content);
        Map resourseMap = new HashMap();//过滤穿过来的布局信息，防止重复下载

        while (matcher.find()) {
            String fileName = matcher.group();
            if (FileUtil.isImage(fileName) || FileUtil.isMusic(fileName) || FileUtil.isVideo(fileName)) {
                if (!resourseMap.containsKey(fileName)) {
                    allResourList.add(fileName);
                }
                resourseMap.put(fileName, fileName);
            }
        }
        return allResourList;
    }

    private static Integer getMoreCharCountByRules(String content, String rules) {
        Pattern pattern = Pattern.compile(rules);
        Matcher matcher = pattern.matcher(content);
        StringBuffer buffer = new StringBuffer();
        Integer count = 0;
        Map countMap = new HashMap();//过滤用
        while (matcher.find()) {
            buffer.append(matcher.group() + "\r\n");
            if (FileUtil.isImage(matcher.group())
                    || FileUtil.isMusic(matcher.group())
                    || FileUtil.isVideo(matcher.group())) {
                if (!countMap.containsKey(matcher.group())) {
                    count++;
                }
                countMap.put(matcher.group(), matcher.group());
            }
        }
        return count;
    }

    /**
     * 获取url的个数
     *
     * @param content
     * @return
     */
    public static Integer getUrlCount(String content) {
        String urlRules = "(http://|https://){1}[\\w\\.\\-/:]+";
        Integer urlCount = getMoreCharCountByRules(content, urlRules);
        return urlCount;
    }

    /**
     * 获取url的个数
     *
     * @param content
     * @return
     */
    public static List getResouceList(String content) {
        String urlRules = "(http://|https://){1}[\\w\\.\\-/:]+";
        List urlCount = getAllLayoutFiles(content, urlRules);
        return urlCount;
    }

    public static JSONArray getResouceArray(String content) {

        content = content.replaceAll("\\\\", "");

        String urlRules = "(http://|https://){1}[\\w\\.\\-/:]+";
        List urlCount = getAllLayoutFiles(content, urlRules);

        JSONArray fileJson = new JSONArray();
        for (int i = 0; i < urlCount.size(); i++) {
            fileJson.put(urlCount.get(i));
        }
        return fileJson;
    }

    public static void deleteDownFile() {
        String layoutStr = LayoutCache.getLayoutCacheAsString();
        List<String> allDownloadList = getResouceList(layoutStr);

        for (int i = 0; i < allDownloadList.size(); i++) {
            String fileName = allDownloadList.get(i);
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
//            String path = RESOURSE_PATH + IMAGE_CACHE_PATH + fileName;
        }
    }

    public static void downloadLevelFile() {
        String layoutStr = LayoutCache.getLayoutCacheAsString();
        List<String> allDownloadList = getResouceList(layoutStr);

        List<String> downLoads = new ArrayList<String>();
        //没有下载完成的集合
        List<String> noDownloads = new ArrayList<String>();

        for (int i = 0; i < allDownloadList.size(); i++) {
            String fileName = allDownloadList.get(i);
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
//            String path = RESOURSE_PATH + IMAGE_CACHE_PATH + fileName;
//            if (new File(path + "_ok").exists()) {//如果存在ok文件就添加到播放列表中
//                if (new File(path).exists()) {
//                    downLoads.add(path);
//                } else {
//                    FileTool.delete(new File(path + "_ok"));
//                }
//            } else {
//                noDownloads.add(path);
//            }
        }
        if (noDownloads.size() > 0) {//如果有未下载完成的文件就重新启动下载的功能
            TYTool.downloadLocalLayoutResource();
        }
    }

    public static String downloadStatus() {
        String layoutStr = LayoutCache.getLayoutCacheAsString();
        List<String> allDownloadList = getResouceList(layoutStr);
        List<String> downLoads = new ArrayList<>();
        List<String> noDownloads = new ArrayList<>();

        for (int i = 0; i < allDownloadList.size(); i++) {
            String fileName = allDownloadList.get(i);
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
//            String path = RESOURSE_PATH + IMAGE_CACHE_PATH + fileName;
//            if (new File(path + "_ok").exists()) {//如果存在ok文件就添加到播放列表中
//                downLoads.add(path);
//            } else {
//                noDownloads.add(path);
//            }
        }
        int allCount = downLoads.size() + noDownloads.size();
        return downLoads.size() + "/" + allCount;
    }

    public static void cleanUserData() {


//        String deviceType = SpUtils.getString(APP.Companion.getAppContext(), SpUtils.DEVICETYPE, "");
//        if (!"1".equals(deviceType)) {
//            FileTool.delete(new File(FaceConstant.SCREEN_SAVE_PATH));
//        }
    }
}
